package top.yaofengqiao.springcloudsimple.auth.biz.domain.security.service;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.auth.model.valobj.Oauth2Type;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.UserInfo;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.model.entity.MemberEntity;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.service.IMemberService;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author yfq
 * @date 2024/6/11 14:20
 * @description
 */
public abstract class Oauth2UserDetailService implements UserDetailsService {
    private final Oauth2Type oauth2Type;
    @Resource
    private IMemberService memberService;

    public Oauth2UserDetailService(Oauth2Type oauth2Type) {
        this.oauth2Type = oauth2Type;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MemberEntity memberEntity = memberService.queryByOpenid(username, oauth2Type);

        UserInfo userInfo = buildUserInfo(memberEntity);

        if (userInfo == null) throw new UsernameNotFoundException("用户不存在");

        userInfo.setRoles(Collections.singletonList("member"));

        return userInfo;
    }

    private UserInfo buildUserInfo(MemberEntity memberEntity) {
        if (memberEntity == null) return null;

        return UserInfo.builder()
                .userId(memberEntity.getId())
                .username(memberEntity.getMobile())
                .password(memberEntity.getPassword())
                .status(memberEntity.getStatus())
                .mobile(memberEntity.getMobile())
                .icon(memberEntity.getAvatar())
                .build();
    }

}
